<template>
  <div>
    <el-form ref="form" label-width="120px" :model="form" :rules="rules">
      <el-form-item label="角色名称" prop="name">
        <el-input placeholder="请填写角色名称" :disabled="isDisabled" v-model="form.name" maxlength="24"></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status" :disabled="isDisabled">
          <el-radio :label="item.value" v-for="item in STATUS_LIST" :key="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input
          :disabled="isDisabled"
          placeholder="请填写角色描述"
          v-model="form.description"
          type="textarea"
          maxlength="300"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="权限">
        <el-tree
          ref="tree"
          :data="permissionsList"
          show-checkbox
          node-key="menuId"
          default-expand-all
          :default-checked-keys="selectPermissionsList"
        ></el-tree>
      </el-form-item>
      <el-form-item class="btns">
        <el-button type="primary" size="small" @click="save()" v-if="!isDisabled">保存</el-button>
        <el-button size="small" @click="cancel()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { STATUS_LIST } from '@/constants/baseModel.js'

export default {
  name: 'roleAddEdit',
  data() {
    return {
      STATUS_LIST,
      permissionsList: [],
      rules: {
        name: [{ required: true, message: '请填写角色名称' }],
      },
      selectPermissionsList: [],
      form: {
        // 角色名称
        name: '',
        // 状态
        status: '1',
        // 角色描述
        description: '',
        // 权限menuIds
        menuIds: [],
      },
    }
  },
  computed: {
    isDisabled() {
      return this.$route.query.type && this.$route.query.type === 'watch' ? true : false
    },
  },
  methods: {
    save() {
      this.$refs['form'].validate(async valid => {
        if (!valid) return
        this.form.menuIds = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
        if (!this.form.menuIds.length) return this.$message.error('请勾选此角色权限~')
        await this.submitRequest()
        this.$router.back(-1)
      })
    },
    cancel() {
      this.$router.back(-1)
    },
    async submitRequest() {
      const url = this.$route.query.roleId ? `/roles/${this.$route.query.roleId}/update` : '/roles/add'
      const method = this.$route.query.roleId ? 'put' : 'post'
      await this.$http[method](url, this.form)
    },
    async getDetailRequest(allPermissionsList) {
      const res = await this.$http.get(`/roles/${this.$route.query.roleId}`)
      this.form.name = res.name
      this.form.status = res.status
      this.form.description = res.description
      let defaultSelectedListsIds = []
      defaultSelectedListsIds = res.menuIds && res.menuIds.length ? res.menuIds : []
      console.log('选中的与半选的值', defaultSelectedListsIds)
      const getAllOfMenuIds = this.getAllTreeListsId(allPermissionsList)
      if (getAllOfMenuIds.length === defaultSelectedListsIds.length) {
        this.selectPermissionsList = defaultSelectedListsIds
        return
      }
      const fatherIds = await this.getFathersIds(allPermissionsList)
      console.log('获取到的所有父级ids', fatherIds)
      const selectedIds = await this.resolveFinallySelectedIds(defaultSelectedListsIds, fatherIds)
      console.info('最终被选中的结果' + selectedIds)
      this.selectPermissionsList = selectedIds
    },
    // 过滤出所有的menuIds
    getAllTreeListsId(allPermissionsList) {
      let treeIds = []
      for (let i = 0; i < allPermissionsList.length; i++) {
        if (Array.isArray(allPermissionsList[i].children)) {
          treeIds.push(allPermissionsList[i].menuId)
          treeIds = treeIds.concat(this.getAllTreeListsId(allPermissionsList[i].children))
        } else {
          treeIds.push(allPermissionsList[i].menuId)
        }
      }
      return treeIds
    },
    // 过滤出所有的parentIds
    getFathersIds(allPermissionsList) {
      let fatherIds = []
      for (let i = 0; i < allPermissionsList.length; i++) {
        if (Array.isArray(allPermissionsList[i].children)) {
          fatherIds.push(allPermissionsList[i].parentId)
          fatherIds = fatherIds.concat(this.getFathersIds(allPermissionsList[i].children))
        }
      }
      return [...new Set(fatherIds)]
    },
    resolveFinallySelectedIds(selectedIds, fatherIds) {
      let newArray = []
      for (let key in selectedIds) {
        let longIds = selectedIds[key]
        let count = 0
        for (let j = 0; j < fatherIds.length; j++) {
          let shortIds = fatherIds[j]
          if (longIds === shortIds) {
            count++
          }
        }
        if (count === 0) {
          newArray.push(longIds)
        }
      }
      return newArray
    },
    async getAllPermissionsRequest() {
      const res = await this.$http.get('/menus')
      this.permissionsList = res
      if (res && res.length && this.$route.query.roleId) {
        if (this.$route.query.type === 'watch') this.permissionsList = this.disabledAllPermission(res)
        await this.getDetailRequest(res)
      }
    },
    // 查看时使用，禁用所有
    disabledAllPermission(allPermissionList) {
      const isDisabled = true
      for (let i = 0; i < allPermissionList.length; i++) {
        if (Array.isArray(allPermissionList[i].children)) {
          allPermissionList[i].disabled = isDisabled
          this.disabledAllPermission(allPermissionList[i].children)
        }
      }
      return allPermissionList
    },
  },
  mounted() {
    this.getAllPermissionsRequest()
  },
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
